﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using Data;
namespace Text1
{
    class GameSever
    {
        static GameSever _instance;
        public static GameSever Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new GameSever();
                }
                return _instance;
            }
        }
        string ip = "192.168.11.22";
        int port = 8500;
        TcpListener listener;
        HandlerCenter center = new HandlerCenter();
        public GameSever()
        {
            IPAddress address = IPAddress.Parse(ip);
            listener = new TcpListener(address, port);
            listener.Start();//开始侦听
            Console.WriteLine("服务器开启");
            listener.BeginAcceptTcpClient(AcceptTep, null);
        }
        void AcceptTep(IAsyncResult ar)
        {
            try
            {
                TcpClient client = listener.EndAcceptTcpClient(ar);//异步接收远程连接
                SockedClient socket = new SockedClient(client);
                string key = client.Client.RemoteEndPoint.ToString();
                ////clients.Add(key, socket);

                listener.BeginAcceptTcpClient(AcceptTep, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        //给单一客户端发送
        public void SendClient<T>(SockedClient client, Protocal type, T t) where T : ProtoBuf.IExtensible
        {
            client.Send(type, ProtoHelper.Serialize<T>(t));
        }
        //广播给其他玩家 我上线
        public void SendOther<T>(SockedClient client, Protocal type, T t) where T : ProtoBuf.IExtensible
        {
            foreach (var item in ActorManager.Instance.actors)
            {
                if (item.Value.client != client)
                {
                    item.Value.client.Send(type, ProtoHelper.Serialize<T>(t));
                }
            }
        }
        public void SendAll<T>(Protocal type, T t) where T : ProtoBuf.IExtensible
        {
            foreach (var item in ActorManager.Instance.actors)
            {
                item.Value.client.Send(type, ProtoHelper.Serialize<T>(t));
            }
        }
        //丢失连接
        public void DisConnect(SockedClient client)
        {         
            ActorManager.Instance.Remove(client);        
        }
        /// <summary>
        /// 接受客户端消息事件分发
        /// </summary>
        /// <param name="buffer">消息[type+content]</param>
        public static void OnEvent(SockedClient client, ByteBuffer buffer)
        {
            Instance.center.RecieveMessage(client, buffer);
        }
    }
}
